<template>
  <div class="login" :style="loginStyle">
    <el-card shadow="always">
      <div class="login-main">
        <div class="login-logo">
          <el-image :src="loginLogo" style="width: 100%; height: 100%;"></el-image>
        </div>
        <div class="login-form">
          <el-form ref="loginRuleForm" :model="loginForm">
            <div class="login-form-title2">学生违纪处分系统</div>
            <div class="login-form-title">欢迎登录</div>
            <el-form-item
              prop="username"
              :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
            >
              <el-input
                v-model="loginForm.username"
                prefix-icon="Avatar"
                placeholder="请输入用户名"
                style="width:100%"
              ></el-input>
            </el-form-item>
            <el-form-item
              prop="password"
              :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
            >
              <el-input
                type="password"
                v-model="loginForm.password"
                prefix-icon="Lock"
                show-password
                placeholder="请输入密码"
                style="width:100%"
              ></el-input>
            </el-form-item>
            <el-form-item prop="verifyStatus">
              <SlidingVerify
                ref="slidingVerify"
                :status="loginForm.verifyStatus"
                :successFun="onVerifySuccess"
                :errorFun="onVerifyError"
              ></SlidingVerify>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" round @click="submit" style="width:100%">
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onBeforeMount } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import SlidingVerify from "@/components/SlidingVerify.vue";
import axios from "axios";
import router from "@/router/index.js";
import {useUserStore} from "@/store/settings.js";
import axiosInstance from "@/router/axios.js";

const loginLogo = new URL("../../assets/image/login-left.png", import.meta.url).href;

const state = reactive({
  loginStyle: {
    height: "",
  },
  loginForm: {
    username: "",
    password: "",
    verifyStatus: null,
  },
});

const { loginStyle, loginForm } = toRefs(state);
// const userStore = useUserStore();
// const useStore = useAuthStore();
const loginRuleForm = ref(null);

onBeforeMount(() => {
  state.loginStyle.height =
    (document.body.clientHeight || document.documentElement.clientHeight) + "px";
});

// 滑块验证成功回调
const onVerifySuccess = (e) => {
  console.log("滑块验证成功, 状态更新为:", e); // Debug log for successful sliding validation
  state.loginForm.verifyStatus = true;
};

// 滑块验证失败回调
const onVerifyError = () => {
  console.log("滑块验证失败, 状态重置"); // Debug log for sliding validation failure
  state.loginForm.verifyStatus = false;
};
let loginInformation = reactive({
      username: "",
      type: 0,
      openId: 0,
      password: "",
      token: ""
    });


// 提交表单
const submit = async () => {
  const form = loginRuleForm.value;

  if (!form) return;

  try {
    await form.validate();

    if (!state.loginForm.verifyStatus) {
      ElMessage.error("请完成滑动验证");
      return;
    }
    var myState = ref();
    try {
      const response = await axios.post('http://localhost:8080/api/login', {
        username: state.loginForm.username,
        password: state.loginForm.password
      });
      myState = response.status
      console.log(myState)
     // 将响应数据存储到响应式对象中
      loginInformation.username = response.data.username;
      loginInformation.type = response.data.type;
      // loginInformation.openId = response.data.openId;
      // loginInformation.password = response.data.password;
      loginInformation.token = response.data.token;
      console.log('Login successful:', response.data);

      await router.push('/main');

      // // Store token in localStorage if login is successful
      // useStore.updateLoginInformation(loginInformation);
      localStorage.setItem('authToken', response.data.token);

      // console.log(response.data.token, "222222")
      const myStore = useUserStore();
      // 用户登录后
      myStore.setUser({token: response.data.token, username:  loginInformation.username,type: response.data.type, loginTime: new Date().toISOString() });
    } catch (error) {
      console.error('Login failed:', error.response || error);

        // Clear password field and show error message
      state.loginForm.password = '';
      ElNotification.error({
        title: "登录失败",
        message: "权限不够",
      });


    }
  } catch (error) {
    if (myState === 402) {
        // Clear password field and show error message
      state.loginForm.password = '';
      ElNotification.error({
        title: "登录失败",
        message: "权限不够",
      });
      }else {
      ElMessage.error("用户名或密码错误，请检查输入");
    }

  }
};
</script>

<style lang="scss" scoped>
.login {
  background-image: url("../../assets/image/login-bg.svg");
  background-size: 100% 100%;
  height: 100%;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;

  .el-card__body {
    padding: 0;
  }

  .login-main {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;

    .login-logo {
      background: var(--theme);
      width: 20rem;
      padding: 8rem 5rem;
      border-top-right-radius: 38px;
      border-bottom-right-radius: 38px;
    }

    .login-form {
      width: 20rem;
      padding: 8rem 5rem;

      .login-form-title {
        font-size: 18px;
        font-weight: 700;
        text-align: center;
        padding-bottom: 2rem;
      }
      .login-form-title2 {
        font-size: 34px;
        font-weight: 700;
        text-align: center;
        padding-bottom: 2rem;
      }
      .el-form-item {
        margin-bottom: 20px;
      }

      .el-button {
        margin-top: 20px;
      }
    }
  }
}
</style>